package com.ccpjcmjs.config;

import com.ccpjcmjs.pojo.User;
import com.ccpjcmjs.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

//自定义 UserRealm
public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=> 授权 -> doGetAuthorizationInfo");
        //SimpleAuthenticationInfo
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //授权
//        info.addStringPermission("user:add");

        //拿到当前登录的对象
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User)subject.getPrincipal();//取出的是 认证中返回的user

        //设置当前用户的权限
        info.addStringPermission(currentUser.getPerms());

        //return info;
        return info;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了=> 认证 -> doGetAuthorizationInfo");

        //用户名，密码 ~ 从数据库中获取
//        String name = "root";   //伪造数据
//        String password = "123456";


        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;

//        if (!userToken.getUsername().equals(name)){   //伪造认证
//            return null; //抛出异常 UnknownAccountException
//        }

        //连接数据库
        User user = userService.queryUserByName(userToken.getUsername());

        if (user==null){ //没有这个人
            return null; //抛出异常 UnknownAccountException
        }

        Subject currentSubject = SecurityUtils.getSubject();
        Session session = currentSubject.getSession();
        session.setAttribute("loginUser",user);

        //密码认证，shiro做  可以加密： MD5
        return new SimpleAuthenticationInfo(user,user.getPwd(),"");
    }
}
